/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.common.utils.ws.jaxrs;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * xxx
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-9-16
 *
 */
@Provider
public class SimpleParamConverterProvider implements ParamConverterProvider {
	
	private static final Logger log = LoggerFactory.getLogger(SimpleParamConverterProvider.class);
	
	private final Map<Class<?>, ParamConverter<?>> paramConverters = new HashMap<Class<?>, ParamConverter<?>>();

	public void registerConverter(Class<?> clazz, ParamConverter<?> converter){
		this.paramConverters.put(clazz, converter);
	}
	
	/* (non-Javadoc)
	 * @see javax.ws.rs.ext.ParamConverterProvider#getConverter(java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[])
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
		ParamConverter<?> converter=this.paramConverters.get(rawType);
		return (ParamConverter<T>)converter;
	}

	public void setParamConverters(List<ParamConverter<?>> paramConverters){
		if(paramConverters!=null && !paramConverters.isEmpty()){
			for(ParamConverter<?> pc : paramConverters){
				Class<?> clazz=getParamConverterGenericClass(pc.getClass());
				this.registerConverter(clazz, pc);
			}
		}
	}
	
	/**
	 * 获取具体ParamConverter类的泛型类型，eg: SearchFiltersParamConverter implements ParamConverter<SearchFilters>
	 * 则返回SearchFilters类型
	 * @param clazz
	 * @return
	 */
	private static final Class<?> getParamConverterGenericClass(Class<?> clazz){
		Type genType = clazz.getGenericSuperclass();
		
		if (!(genType instanceof ParameterizedType)) {
			genType=null;
			Type[] genTypes = clazz.getGenericInterfaces();
			if(genTypes!=null && genTypes.length>0){
				if (genTypes[0] instanceof ParameterizedType){
					genType=genTypes[0];
				}
			}
			if(genType==null){
				log.warn(clazz.getSimpleName() + "'s superclass or implements interface not ParameterizedType");
				return Object.class;
			}
		}

		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		if (!(params[0] instanceof Class)) {
			log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
			return Object.class;
		}
		return (Class<?>)params[0];
	}
}
